<script setup>
import { ref, onMounted, computed } from 'vue'
import { listSamples, listIndicatorResults, updateIndicatorResult } from '../../api/common'
import { doctorUpdateSampleStatus, doctorCreateIndicatorResult } from '../../api/doctor'
import { listIndicators, listPackageItems } from '../../api/admin'
import { getOrder } from '../../api/user'
import { ElMessage } from 'element-plus'

const list = ref([])
const total = ref(0)
const query = ref({ orderId: '', sampleId: '', sampleType: '', status: '', page: 1, size: 10 })
const loading = ref(false)
const statusDialog = ref(false)
const statusForm = ref({ sampleId: null, status: '', remark: '' })

// 状态数字化映射
// 数字 → 文本（用于展示）
const statusTextByCode = {
  1: '采集中',
  2: '采集成功',
  3: '异常',
  4: '完成',
}
// 兼容映射：如果后端返回或仍存有字符串，映射到数字；数字保持自身
// 后端或历史数据中的字符串/中文 → 数字（用于展示与编辑）
const codeOfStatusString = {
  1: 1,
  2: 2,
  3: 3,
  4: 4,
  '采集中': 1,
  '正在采集': 1,
  '采集成功': 2,
  '已采集': 2,
  '采集完成': 2,
  '异常': 3,
  '完成': 4,
  // 兼容历史英文值
  COLLECTING: 1,
  COLLECTED: 2,
  ABNORMAL: 3,
  TESTED: 4,
  DONE: 4,
}

// 指标录入
const indicatorDialog = ref(false)
const indicatorForm = ref({ sampleId: '', indicatorId: '', resultValue: '', doctorComment: '' })
const indicatorOptions = ref([])
const indicatorMetaById = ref({})
const currentIndicatorMeta = computed(() => indicatorMetaById.value[indicatorForm.value.indicatorId] || null)

// 指标模板批量录入
const templateDialog = ref(false)
const templateSampleId = ref(null)
const templateIndicators = ref([]) // { indicatorId, name, unit }
const templateValues = ref({}) // { [indicatorId]: value }
const templateDoctorComment = ref('')

const loadTemplateForSample = async (row) => {
  templateSampleId.value = row.sampleId
  templateIndicators.value = []
  templateValues.value = {}
  templateDoctorComment.value = ''
  try {
    const order = await getOrder(row.orderId)
    if (!order) return
    let ids = []
    if (order.orderType === 'PACKAGE' && order.packageId) {
      const items = await listPackageItems(order.packageId)
      ids = (items || []).map(it => it.indicatorId)
    } else if (order.orderType === 'INDICATOR' && order.indicatorId) {
      ids = [order.indicatorId]
    }
    if (ids.length) {
      const indRes = await listIndicators({ page: 1, size: 500 })
      const metaMap = Object.fromEntries(((indRes?.list) || []).map(i => [i.indicatorId, i]))
      templateIndicators.value = ids.map(id => {
        const m = metaMap[id] || {}
        return { indicatorId: id, name: m.indicatorName || `指标#${id}`, unit: m.unit || '' }
      })
    }
  } catch (e) {
    // ignore
  }
}

const openTemplateDialog = async (row) => {
  await loadTemplateForSample(row)
  templateDialog.value = true
}

const submitTemplateResults = async () => {
  if (!templateSampleId.value) return ElMessage.error('缺少标本ID')
  const entries = Object.entries(templateValues.value).filter(([_, v]) => v !== '' && v !== undefined)
  if (!entries.length) return ElMessage.error('请填写至少一个指标的结果值')
  loading.value = true
  try {
    let count = 0
    for (const [indicatorId, value] of entries) {
      await doctorCreateIndicatorResult({
        sampleId: templateSampleId.value,
        indicatorId: Number(indicatorId),
        resultValue: value,
        doctorComment: templateDoctorComment.value || undefined,
      })
      count++
    }
    ElMessage.success(`已保存 ${count} 项指标结果`)
    templateDialog.value = false
    templateValues.value = {}
  } finally {
    loading.value = false
  }
}

const fetchList = async () => {
  loading.value = true
  try {
    const data = await listSamples({
      orderId: query.value.orderId || undefined,
      sampleId: query.value.sampleId || undefined,
      sampleType: query.value.sampleType || undefined,
      status: query.value.status || undefined,
      page: query.value.page,
      size: query.value.size,
    })
    list.value = data.list || []
    total.value = data.total || 0
  } finally { loading.value = false }
}

const openStatusDialog = (row) => {
  statusForm.value.sampleId = row.sampleId
  statusForm.value.status = codeOfStatusString[row.status] ?? row.status ?? ''
  statusForm.value.remark = ''
  statusDialog.value = true
}

const submitStatus = async () => {
  if (!statusForm.value.sampleId) {
    ElMessage.error('标本ID缺失，无法更新状态')
    return
  }
  loading.value = true
  try {
    const statusCode = statusForm.value.status
    if (!statusCode) {
      ElMessage.error('请选择有效的状态')
      return
    }
    await doctorUpdateSampleStatus(statusForm.value.sampleId, { status: statusCode, remark: statusForm.value.remark || undefined })
    ElMessage.success('状态更新成功')
    statusDialog.value = false
    fetchList()
  } finally { loading.value = false }
}

const ensureIndicatorOptionsForSample = async (sampleType) => {
  try {
    const data = await listIndicators({ page: 1, size: 500 })
    const list = (data.list || []).filter(i => !sampleType || i.specimenType === sampleType)
    indicatorOptions.value = list.map(i => ({ value: i.indicatorId, label: `${i.indicatorName}${i.unit ? `（${i.unit}）` : ''}` }))
    indicatorMetaById.value = Object.fromEntries(list.map(i => [i.indicatorId, i]))
  } catch (e) {
    indicatorOptions.value = []
    indicatorMetaById.value = {}
  }
}

const openIndicatorDialog = async (row) => {
  indicatorForm.value = { sampleId: row.sampleId, indicatorId: '', resultValue: '', doctorComment: '' }
  await ensureIndicatorOptionsForSample(row.sampleType)
  indicatorDialog.value = true
}

const submitIndicator = async () => {
  if (!indicatorForm.value.sampleId) return ElMessage.error('缺少标本ID')
  if (!indicatorForm.value.indicatorId) return ElMessage.error('请选择指标')
  if (indicatorForm.value.resultValue === '') return ElMessage.error('请输入结果值')
  loading.value = true
  try {
    // 自动异常判定
    const meta = currentIndicatorMeta.value
    let abnormalFlag
    const valNum = Number(indicatorForm.value.resultValue)
    if (meta && !Number.isNaN(valNum)) {
      const hasLower = meta.lowerLimit !== undefined && meta.lowerLimit !== null && meta.lowerLimit !== ''
      const hasUpper = meta.upperLimit !== undefined && meta.upperLimit !== null && meta.upperLimit !== ''
      if (hasLower || hasUpper) {
        if (hasLower && valNum < Number(meta.lowerLimit)) abnormalFlag = true
        else if (hasUpper && valNum > Number(meta.upperLimit)) abnormalFlag = true
        else abnormalFlag = false
      }
    }

    // 先查是否已存在结果，存在则走更新避免重复
    const existed = await listIndicatorResults({ sampleId: indicatorForm.value.sampleId, indicatorId: indicatorForm.value.indicatorId, page: 1, size: 1 })
    const existingId = (existed.list && existed.list[0] && existed.list[0].resultId) || null
    if (existingId) {
      await updateIndicatorResult(existingId, {
        resultValue: indicatorForm.value.resultValue,
        abnormalFlag: abnormalFlag !== undefined ? abnormalFlag : undefined,
        doctorComment: indicatorForm.value.doctorComment || undefined,
      })
      ElMessage.success('已更新现有指标结果')
    } else {
      await doctorCreateIndicatorResult({
        sampleId: indicatorForm.value.sampleId,
        indicatorId: indicatorForm.value.indicatorId,
        resultValue: indicatorForm.value.resultValue,
        abnormalFlag: abnormalFlag !== undefined ? abnormalFlag : undefined,
        doctorComment: indicatorForm.value.doctorComment || undefined
      })
      ElMessage.success('指标录入成功')
    }
    indicatorDialog.value = false
    indicatorForm.value = { sampleId: '', indicatorId: '', resultValue: '', doctorComment: '' }
  } finally {
    loading.value = false
  }
}

onMounted(fetchList)
</script>

<template>
  <el-card>
    <h3>样本采集管理</h3>
    <el-form :inline="true" :model="query" class="mb-2">
      <el-form-item label="订单ID"><el-input v-model="query.orderId" /></el-form-item>
      <el-form-item label="标本ID"><el-input v-model="query.sampleId" /></el-form-item>
      <el-form-item label="类型"><el-input v-model="query.sampleType" /></el-form-item>
      <el-form-item label="状态">
        <el-select v-model="query.status" placeholder="全部" style="width:180px">
          <el-option label="全部" :value="''" />
          <el-option label="1 采集中" :value="1" />
          <el-option label="2 采集成功" :value="2" />
          <el-option label="3 异常" :value="3" />
          <el-option label="4 完成" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="query.page=1;fetchList()">查询</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="list" v-loading="loading" style="width:100%">
      <el-table-column prop="sampleId" label="标本ID" width="90" />
      <el-table-column prop="orderId" label="订单ID" width="100" />
      <el-table-column prop="sampleType" label="类型" />
      <el-table-column label="状态">
        <template #default="{ row }">
          <span v-if="codeOfStatusString[row.status]">
            {{ codeOfStatusString[row.status] }} {{ statusTextByCode[codeOfStatusString[row.status]] }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" />
      <el-table-column label="操作" width="360">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="openStatusDialog(row)">更新状态</el-button>
          <el-button size="small" type="success" @click="openIndicatorDialog(row)">录入指标</el-button>
          <el-button size="small" type="warning" @click="openTemplateDialog(row)">模板批量录入</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="mt-2">
      <el-pagination background layout="total, prev, pager, next" :total="total" :page-size="query.size" :current-page="query.page" @current-change="(p)=>{query.page=p;fetchList()}" />
    </div>
  </el-card>

  <el-dialog v-model="statusDialog" title="更新标本状态" width="420px">
    <el-form :model="statusForm" label-width="100px">
      <el-form-item label="状态">
        <el-select v-model="statusForm.status" style="width:220px">
          <el-option label="1 采集中" :value="1" />
          <el-option label="2 采集成功" :value="2" />
          <el-option label="3 异常" :value="3" />
          <el-option label="4 完成" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注"><el-input v-model="statusForm.remark" /></el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="statusDialog=false">取消</el-button>
      <el-button type="primary" :loading="loading" @click="submitStatus">提交</el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="indicatorDialog" title="录入指标结果" width="480px">
    <el-form :model="indicatorForm" label-width="120px">
      <el-form-item label="标本ID"><el-input v-model="indicatorForm.sampleId" disabled /></el-form-item>
      <el-form-item label="指标">
        <el-select v-model="indicatorForm.indicatorId" placeholder="选择指标">
          <el-option v-for="opt in indicatorOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="currentIndicatorMeta" label="参考范围">
        <span>{{ currentIndicatorMeta.lowerLimit ?? '-' }} ~ {{ currentIndicatorMeta.upperLimit ?? '-' }} {{ currentIndicatorMeta.unit || '' }}</span>
      </el-form-item>
      <el-form-item label="结果值"><el-input v-model="indicatorForm.resultValue" /></el-form-item>
      <el-form-item label="医生备注"><el-input v-model="indicatorForm.doctorComment" type="textarea" /></el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="indicatorDialog=false">取消</el-button>
      <el-button type="primary" :loading="loading" @click="submitIndicator">提交</el-button>
    </template>
  </el-dialog>

  <!-- 新增：模板批量录入对话框 -->
  <el-dialog v-model="templateDialog" title="模板批量录入指标结果" width="640px">
    <div class="mb-2">标本ID：{{ templateSampleId || '-' }}</div>
    <el-form label-width="140px">
      <div v-if="templateIndicators.length === 0" class="mb-2">未加载到模板项目，可能为单项订单或加载失败</div>
      <el-form-item v-for="it in templateIndicators" :key="it.indicatorId" :label="`${it.name}${it.unit?`（${it.unit}）`:''}`">
        <el-input v-model="templateValues[it.indicatorId]" placeholder="请输入结果值" />
      </el-form-item>
      <el-form-item label="医生备注"><el-input v-model="templateDoctorComment" type="textarea" placeholder="统一备注（可选）" /></el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="templateDialog=false">取消</el-button>
      <el-button type="primary" :loading="loading" @click="submitTemplateResults">保存</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.mb-2{ margin-bottom:12px; }
.mt-2{ margin-top:12px; }
</style>